package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.utility.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@CrossOrigin
public class UserController {


    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     * @param name
     * @param password
     * @return Result
     */
    @GetMapping("/user")
    public ResponseEntity<Result> getUser(@RequestParam String name, @RequestParam String password) {
        System.out.println(name+password);
        User user = userMapper.findByUsernameAndPassword(name, password);
        if (user != null) {
            Result result = new Result(200, "登录成功", user);
            return ResponseEntity.ok(result);  // 返回 200 OK 响应
        } else {
            Result result = new Result(404, "账号或密码错误", null);
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);  // 返回 404 Not Found 响应
        }
    }

    /**
     * 注册
     * @param user
     * @return Result
     */
    @PostMapping("/addUser")
    public ResponseEntity<Result> addUser(@RequestBody User user){
        //随机生成一个UUID对象
        UUID uuid = UUID.randomUUID();
        user.setQqId(uuid.toString());
        //进行条件匹配
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",user.getName()); //将表字段的值，和当前传递对象的参数做对比
        User UserselectOne = userMapper.selectOne(queryWrapper);
        System.out.println(UserselectOne);
        //如果表中没有当前传入的用户名
        if (UserselectOne == null){
            userMapper.insert(user);
            Result result = new Result(200, "注册成功", user);
            return ResponseEntity.ok(result);
        }else {
            Result result = new Result(404, "当前用户名已被占用", null);
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);  // 返回 404 Not Found 响应
        }
    }


}
